<template>
  <el-dialog v-model="dialogVisible" title="新增学员" width="90%" :before-close="handleClose">
    <el-form :model="formInline" :inline="true" class="grids gridColumns5">
      <el-form-item label="年份">
        <DatePicker v-model="formInline.year" type="year"></DatePicker>
      </el-form-item>
      <el-form-item label="学员姓名">
        <el-input v-model="formInline.name" placeholder="学员姓名" clearable />
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="formInline.mobile" placeholder="联系方式" clearable />
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="formInline.identityCard" placeholder="身份证号" clearable />
      </el-form-item>
      <el-form-item label="所在企业">
        <el-input v-model="formInline.enterprise" placeholder="所在企业" clearable />
      </el-form-item>
      <el-form-item label="报名所属">
        <dictSelect v-model="formInline.affiliation" dictCode="registration_affiliation" multiple="1"></dictSelect>
      </el-form-item>
      <el-form-item label="报名状态">
        <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2" clearable v-model="formInline.status" placeholder="请选择报名状态" @change='search'>
          <el-option v-for="(item,index) in tabs" :key="index" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="课程名称">
        <courseQuery v-model="formInline.curriculumId"></courseQuery>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <!-- <el-button>重置</el-button> -->
      </el-form-item>
    </el-form>

    <el-table max-height="30vh" v-loading="loading" size="small" @select-all="selectAll" :data="tableParmas.rows" @select="handleSelectionChange" ref="tableRef">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="approvalContent.model.name" label="姓名" width="100" show-overflow-tooltip />
      <el-table-column prop="approvalContent.model.mobile" label="联系方式" width="120" />
      <el-table-column prop="approvalContent.model.identityCard" label="身份证号" width="180" />
      <el-table-column prop="approvalContent.model.enterprise" label="所在企业名称" width="220" show-overflow-tooltip />
      <el-table-column prop="address" label="报名所属" width="150">
        <template #default="scope">
          {{affiliation_format(scope.row.approvalContent.model.affiliation)}}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="学员来源" width="250">
        <template #default="scope">
          <el-popover placement="right" :width="200" trigger="click" v-if="proxy.$utils.isNumber(form_format(scope.row))">
            <template #reference>
              <el-button type="primary" text>{{form_format(scope.row)}}</el-button>
            </template>
            <el-table :data="scope.row.studentSourceList">
              <el-table-column prop="source" label="学员来源" width="120" />
            </el-table>
          </el-popover>
          <div v-else>{{form_format(scope.row)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="curriculum_Info.name" label="课程名称" min-width="300" show-overflow-tooltip />
      <el-table-column prop="price" label="报名状态" width="120" align="center" fixed="right">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.status == 1 && scope.row.rejectMsg">已驳回</el-tag>
          <el-tag v-else :color="counter.tagBgColor(scope.row.status)">
            <div :style="{color:counter.tagColor(scope.row.status)}">{{status_format(scope.row.status)}}</div>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="课程价格" fixed="right">
        <template #default="scope">
          {{proxy.$utils.formatNumber(scope.row.price)}}
        </template>
      </el-table-column>
    </el-table>

    <pagination :selectNum="selected.length" v-if="tableParmas['total']" :total="tableParmas['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <div class="title bold">已选学员</div>
    <el-table size="small" :data="paginatedData" max-height="20vh" ref="multipleTable" @select="selectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="approvalContent.model.name" label="姓名" width="100" show-overflow-tooltip />
      <el-table-column prop="approvalContent.model.mobile" label="联系方式" width="120" />
      <el-table-column prop="approvalContent.model.identityCard" label="身份证号" width="180" />
      <el-table-column prop="approvalContent.model.enterprise" label="所在企业名称" width="220" show-overflow-tooltip />
      <el-table-column prop="address" label="报名所属" width="150">
        <template #default="scope">
          {{affiliation_format(scope.row.approvalContent.model.affiliation)}}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="学员来源" width="250">
        <template #default="scope">
          <el-popover placement="right" :width="200" trigger="click" v-if="proxy.$utils.isNumber(form_format(scope.row))">
            <template #reference>
              <el-button type="primary" text>{{form_format(scope.row)}}</el-button>
            </template>
            <el-table :data="scope.row.studentSourceList">
              <el-table-column prop="source" label="学员来源" width="120" />
            </el-table>
          </el-popover>
          <div v-else>{{form_format(scope.row)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="curriculum_Info.name" label="课程名称" min-width="300" show-overflow-tooltip />
      <el-table-column prop="price" label="报名状态" width="120" align="center" fixed="right">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.status == 1 && scope.row.rejectMsg">已驳回</el-tag>
          <el-tag v-else :color="counter.tagBgColor(scope.row.status)">
            <div :style="{color:counter.tagColor(scope.row.status)}">{{status_format(scope.row.status)}}</div>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="课程价格" fixed="right">
        <template #default="scope">
          {{proxy.$utils.formatNumber(scope.row.price)}}
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination flex justifyEnd">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="selected.length">
      </el-pagination>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const emit = defineEmits(["fatherMethod"]);

const { proxy } = getCurrentInstance();

let dialogVisible = ref(false);
let formInline = ref({
  curriculumId: "",
  identityCard: "",
  mobile: "",
  name: "",
  enterprise: "",
  affiliation: [],
  studentSourceList: [],
  status: "",
  year: proxy.$utils.dateTimeFormateFn(new Date(), "year"),
  pageIndex: 1,
  pageSize: 50,
});
let info = {}; //班级信息
let tableParmas = ref({});
let tabs = ref([
  { name: "未支付", value: 0 },
  { name: "订单取消", value: 6 },
  { name: "待审核", value: 1 },
  { name: "审核未通过", value: 3 },
  { name: "支付尾款", value: 8 },
  { name: "报名成功", value: 2 },
  { name: "已退款", value: 4 },
  { name: "部分退款", value: 9 },
  { name: "已开票", value: 7 },
]);
let selected = ref([]); //选中的学生
let loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return selected.value.slice(start, end);
});

let handleSelect = computed(() => {
  let arr = [];
  let list = proxy.$utils.deepcopy(selected.value);
  list.forEach((element) => {
    let obj = {
      curriculum_id: element.curriculum_id, //课程id
      userId: element.userId, //用户id
      classId: info["_id"], //班级id
      orderId: element._id, //订单id
    };
    arr.push(obj);
  });
  return proxy.$utils.uniqueByFields(arr, "classId", "orderId");
});

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  nextTick(() => {
    proxy.$refs.multipleTable.toggleAllSelection();
  });
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  nextTick(() => {
    proxy.$refs.multipleTable.toggleAllSelection();
  });
};

function handleSelectionChange(e, k) {
  if (proxy.$utils.isFieldEqual(e, "_id", k._id)) {
    selected.value.push(k);
  } else {
    let index = proxy.$utils.findIndexByField(selected.value, "_id", k._id);
    if (index != -1) selected.value.splice(index, 1);
  }
}

function selectAll(array) {
  if (array.length) {
    array.forEach((element) => {
      if (proxy.$utils.isFieldEqual(selected.value, "_id", element._id)) {
      } else {
        selected.value.push(element);
      }
    });
  } else {
    tableParmas.value.rows.forEach((element) => {
      let index = proxy.$utils.findIndexByField(
        selected.value,
        "_id",
        element._id
      );
      if (index != -1) selected.value.splice(index, 1);
    });
  }
}

async function submit() {
  try {
    loading.value = true;
    let list = proxy.$utils.deepcopy(handleSelect.value);
    if (!list.length) return proxy.$utils.showToast("请选择学生", 0);
    //return console.log("list", list);
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      element.userState = 1; //状态
      await proxy.$apis.classStudent({
        type: "add",
        data: element,
      });
    }
    proxy.$utils.showToast("添加成功");
    handleClose();
  } catch (error) {
    console.log("什么问题", error);
  } finally {
    loading.value = false;
  }
}

function status_format(e) {
  for (let index = 0; index < tabs.value.length; index++) {
    const element = tabs.value[index];
    if (element.value == e) return element.name;
  }
}

function open(data) {
  info = { ...data };
  formInline.value.curriculumId = data.curriculumId;
  formInline.value.year = proxy.$utils.dateTimeFormateFn(
    data._add_time,
    "year"
  );
  formInline.value.classId = data._id;
  getInfo();
  dialogVisible.value = true;
}

function init() {
  formInline.value = {
    curriculumId: "",
    identityCard: "",
    mobile: "",
    name: "",
    enterprise: "",
    affiliation: [],
    studentSourceList: [],
    status: "",
    pageIndex: 1,
    pageSize: 10,
  };
  formInline.value.curriculumId = info["curriculumId"];
  formInline.value.year = info["_add_time"];
  getInfo();
}

function search() {
  formInline.value.pageIndex = 1;
  getInfo();
}

function handleClose() {
  formInline.value = {
    curriculumId: "",
    identityCard: "",
    mobile: "",
    name: "",
    enterprise: "",
    affiliation: [],
    studentSourceList: [],
    pageIndex: 1,
    pageSize: 10,
  };
  emit("fatherMethod");
  selected.value = [];
  dialogVisible.value = false;
}

function form_format(row) {
  if (!row.user_Info.studentSourceList) return "-";
  let arr = row.user_Info.studentSourceList || [];
  if (arr.length == 1) {
    return arr[0].source;
  } else if (!arr.length) {
    return "-";
  } else {
    return arr.length;
  }
}

function affiliation_format(e) {
  if (!e) return "-";
  if (proxy.$utils.isString(e)) {
    return e;
  } else if (proxy.$utils.isArrayOrJsonArray(e)) {
    return e.toString();
  } else {
    return "-";
  }
}

function selectionChange(e, f) {
  let index = proxy.$utils.findIndexByField(selected.value, "_id", f._id);
  if (index != -1) {
    selected.value.splice(index, 1);
    proxy.$refs.tableRef.clearSelection();
    proxy.$refs.multipleTable.clearSelection();
    nextTick(() => {
      selected.value.forEach((element) => {
        let a = tableParmas.value.rows.find((el) => {
          return element._id == el._id; // 注意这里寻找的字段要唯一，示例仅参考
        });
        if (a) proxy.$refs.tableRef.toggleRowSelection(a, true);
      });
    });
  }
}

async function getInfo() {
  try {
    loading.value = true;
    tableParmas.value = await proxy.$apis.classStudent({
      type: "orders",
      data: formInline.value,
    });
    nextTick(() => {
      selected.value.forEach((element) => {
        let a = tableParmas.value.rows.find((el) => {
          return element._id == el._id; // 注意这里寻找的字段要唯一，示例仅参考
        });
        if (a) proxy.$refs.tableRef.toggleRowSelection(a, true);
      });
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}

watch(
  () => selected.value,
  (newValue, oldValue) => {
    if (newValue) {
      nextTick(() => {
        proxy.$refs.multipleTable &&
          proxy.$refs.multipleTable.toggleAllSelection();
      });
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => [
    formInline.value.curriculumId,
    formInline.value.year,
    formInline.value.enterprise,
    formInline.value.mobile,
    formInline.value.name,
    formInline.value.identityCard,
    formInline.value.affiliation,
  ],
  (newValue, oldValue) => {
    if (newValue) search();
  },
  { deep: true, immediate: true }
);

defineExpose({ open });
</script>



<style lang="scss" scoped>
.el-tag {
  border-color: transparent;
}
.title {
  font-size: 16px;
  margin: 20px 0 15px;
}
.pagination {
  margin-top: 15px;
}
</style>